package com.huiben.app.cartoonbooks.app;

import android.os.AsyncTask;
import android.util.Log;

import com.kymjs.rxvolley.toolbox.HttpStatus;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by TwoSX on 2016/6/3.
 */
public class DownloadAsyncTask extends AsyncTask<String, Long, File> {

    private onDownloadListener mOnDownloadListener;
    private long totalSize = 0;
    private boolean isDwon = true;

    public DownloadAsyncTask(onDownloadListener onDownloadListener) {
        mOnDownloadListener = onDownloadListener;
    }

    public void setDwon(boolean dwon) {
        isDwon = dwon;
    }

    @Override
    protected File doInBackground(String... params) {
        String filePath = params[0];
        String urlStr = params[1];
        BufferedInputStream bis = null;
        RandomAccessFile raf = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(8000);
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("Connection", "Keep-Alive");
            bis = new BufferedInputStream(connection.getInputStream());
            connection.connect();

            // 判断请求是否成功处理
            if (connection.getResponseCode() == HttpStatus.SC_OK) {
                totalSize = connection.getContentLength();
                raf = new RandomAccessFile(new File(filePath), "rw");
                raf.setLength(totalSize);
                byte[] bys = new byte[2 * 1024];
                long transferredBytes = 0;
                int len = 0;
                while ((len = bis.read(bys)) != -1 && isDwon) {
                    raf.write(bys, 0, len);
                    transferredBytes += len;
                    if (mOnDownloadListener != null) {
                        mOnDownloadListener.onProgress(transferredBytes, totalSize);
                    }
                }
                if (!isDwon)
                    return null;
            } else {
                return null;
            }


        } catch (Exception e) {
           e.printStackTrace();
                Log.e("DownloadAsyncTask", "下载出错");
            return null;
        } finally {
            try {
                if (bis != null)
                    bis.close();
                if (raf != null)
                    raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return new File(filePath);
    }


    @Override
    protected void onPostExecute(File file) {
        super.onPostExecute(file);
        if (file != null) {
            if (mOnDownloadListener != null) {
                try {

                        Log.e("DownloadAsyncTask", "下载完成");

                        Log.e("DownloadAsyncTask", file.getName());

                        Log.e("DownloadAsyncTask", file.getParent());

                        Log.e("DownloadAsyncTask", "------------------------------");
                    File file1 = new File(file.getParent(), file.getName() + ".ok");
                    if (!file1.exists()) {

                            Log.e("DownloadAsyncTask", "创建标记文件");
                        file1.createNewFile();




                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                mOnDownloadListener.onSuccess();
            }
        } else {
            if (mOnDownloadListener != null)
                mOnDownloadListener.onFailure();
        }
    }


    public interface onDownloadListener {

        /**
         * 回调下载进度
         *
         * @param transferredBytes 已经下载的字节
         * @param totalSize        总字节
         */
        void onProgress(long transferredBytes, long totalSize);

        void onSuccess();

        void onFailure();

    }

}
